
//
//  MainViewController.m
//  WHSport
//
//  Created by ccjoy-jimneylee on 15/3/26.
//  Copyright (c) 2015年 jimneylee. All rights reserved.
//

#import "MainViewController.h"
#import "LoginViewC.h"
#import "VenuelistViewC.h"
#import "PlaceDetailViewC.h"
#import "Util.h"
#import "WarViewController.h"
#import "CompetitionoViewC.h"
#import "UserModel.h"
#import "MemberCenterViewC.h"
#import "BusinessModel.h"
#import <UIImageView+AFNetworking.h>

@interface MainListCell : UITableViewCell
@property(nonatomic, weak) IBOutlet UIImageView *placeImg;
@property(nonatomic, weak) IBOutlet UIImageView *levelImg;
@property(nonatomic, weak) IBOutlet UILabel *nameLab;
@property(nonatomic, weak) IBOutlet UILabel *evaLab;
@property(nonatomic, weak) IBOutlet UILabel *nowLab;
@property(nonatomic, weak) IBOutlet UILabel *oriLab;
@property(nonatomic, weak) IBOutlet UILabel *placeLab;
@property(nonatomic, weak) IBOutlet UILabel *disLab;

@end
@implementation  MainListCell

@end

@interface MyCollectionCell : UICollectionViewCell
@property (nonatomic,weak) IBOutlet UIImageView *imageView;
@property (nonatomic,weak) IBOutlet UILabel *titleLable;
@end
@implementation  MyCollectionCell

@end

@interface MainViewController (){
    
    NSArray *headImage;
    NSArray *titleLable;
    NSString *nober;
    NSArray *dataArray;
    NSArray *photoArray;
}

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title =@"挥汗网";
    [self getPhoto];
    _collectionView.contentSize = CGSizeMake(MAIN_SCREEN_SIZE.width *2,_collectionView.frame.size.height);
    _collectionView.delegate =self;
    _collectionView.dataSource = self;
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
                                 initWithImage:[UIImage imageNamed:@"person_infor"]
                                 style:UIBarButtonItemStylePlain
                                 target:self action:@selector(center)];
    self.navigationItem.rightBarButtonItem =rightBtn;
    _wonderBtn.layer.borderWidth = 1;
    _wonderBtn.layer.borderColor = RGBCOLOR(16, 191, 229).CGColor;
    
    headImage =@[@"ico_shuttlecock",@"ico_pingpong",@"ico_football",
                 @"ico_basketball",@"ico_tennis",@"ico_table",@"ico_fish",
                 @"ico_climb"];
    titleLable =@[@"羽毛球",@"乒乓球",@"足球",@"篮球",@"网球",
                  @"台球",@"钓鱼",@"攀岩"];
    nober =@"1";
    [self getData];
    
    self.scrollView = [[UIScrollView alloc]
                       initWithFrame:
                       CGRectMake(0,
                                  0,
                                  MAIN_SCREEN_SIZE.width,
                                  self.photoView.frame.size.height)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bouncesZoom = NO;
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    [self.photoView addSubview:self.scrollView];
    
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。
        _locationManager.distanceFilter = 2000.0f;
        
        SEL method = NSSelectorFromString(@"requestAlwaysAuthorization");
        if ([_locationManager respondsToSelector:method]) {
            [_locationManager requestAlwaysAuthorization];
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                [_locationManager requestWhenInUseAuthorization];
                //使用程序其间允许访问位置数据
            }
        }
    }

    
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_locationManager startUpdatingLocation];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_locationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation * currLocation = [locations lastObject];
    self.latitude = [NSString stringWithFormat:@"%f",currLocation.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f",currLocation.coordinate.longitude];
//    NSLog(@"%@,%@",self.latitude,self.longitude);
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if ([error code]==kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code]==kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}


- (void)center{
    
    if ([[UserModel sharedInstance] isOnline]) {
        
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                       bundle:nil];
        MemberCenterViewC *memvc = [main instantiateViewControllerWithIdentifier:@"MemberCenterViewC"];
        [self.navigationController pushViewController:memvc animated:YES];
    }
    else{
        [Util presentLoginControllerFromViewController:self];
   
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)likeBtn:(id)sender{
    [_likeBtn setBackgroundColor:RGBCOLOR(16, 191, 229)];
    [_wonderBtn setBackgroundColor:[UIColor clearColor]];
    [_likeBtn setTitleColor:[UIColor whiteColor] forState:
     UIControlStateNormal];
    [_wonderBtn setTitleColor:RGBCOLOR(16, 191, 229) forState:
     UIControlStateNormal];
    nober =@"1";
    [self getData];

}
- (IBAction)wonderBtn:(id)sender{
    [_wonderBtn setBackgroundColor:RGBCOLOR(16, 191, 229)];
    [_likeBtn setBackgroundColor:[UIColor clearColor]];
    [_wonderBtn setTitleColor:[UIColor whiteColor] forState:
     UIControlStateNormal];
    [_likeBtn setTitleColor:RGBCOLOR(16, 191, 229) forState:
     UIControlStateNormal];

    _likeBtn.layer.borderWidth = 1;
    _likeBtn.layer.borderColor = RGBCOLOR(16, 191, 229).CGColor;
    nober =@"2";
    [self getData];

}

- (void)getData
{
    NSString *latitude =@"31.47";
    NSString *longitude =@"119.58";
    [[BusinessModel sharedInstance]
     getMainListWithLatitude:latitude
     longitude:longitude
     getMain:^(id info) {
        NSArray *array = [info copy];
        dataArray = array;
        [self.tableView reloadData];
    }];
}

- (void)getPhoto{
    
    [[BusinessModel sharedInstance] getPhoto:^(id info) {
        NSArray *photo = [info copy];
        photoArray = photo;
        [self refreshAds];
    }];
}

- (void)refreshAds {
    
    self.scrollView.contentSize =
    CGSizeMake(MAIN_SCREEN_SIZE.width * photoArray.count,
               CGRectGetHeight(self.scrollView.frame));
    [self setupScrollViewImages];
    
    [self.photoView bringSubviewToFront:self.backView];
    self.pageControl.numberOfPages = photoArray.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger pageIndex = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
    self.pageControl.currentPage = pageIndex;
}

- (void)setupScrollViewImages {
    [photoArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary *dic = obj;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:
                                  CGRectMake(MAIN_SCREEN_SIZE.width * idx,
                                             0,
                                             MAIN_SCREEN_SIZE.width,
                                             CGRectGetHeight(self.photoView.frame))];
        imageView.contentMode = UIViewContentModeRedraw;
        NSString *imageUrl = [NSString stringWithFormat:@"http://218.93.12.178:8080/hhw-api/%@",dic];
        [imageView setImageWithURL:[NSURL URLWithString:imageUrl]];
        [_scrollView addSubview:imageView];
    }];
}



#pragma mark-----UIScrollViewDelegate---------
////实现协议UIScrollViewDelegate的方法，必须实现的
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    //获取当前视图的宽度
//    CGFloat pageWith = _collectionView.frame.size.width;
//    //根据scrolView的左右滑动,对pageCotrol的当前指示器进行切换(设置currentPage)
//    int page = floor((scrollView.contentOffset.x - pageWith/2)/pageWith)+1;
//    //切换改变页码，小圆点
//    _pageControl.currentPage = page;
//}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    NSInteger pageIndex = scrollView.contentOffset.x / CGRectGetWidth(_collectionView.frame);
//    
//      _pageControl.currentPage = pageIndex;
//}

#pragma mark - Collection view
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 8;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *collectionCellID = @"MyCollectionCell";
    
    
    MyCollectionCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];
    
    
    NSString *image = [NSString stringWithFormat:@"%@.png",
                       headImage[indexPath.row]];
    cell.imageView.image = [UIImage imageNamed:image];
    cell.titleLable.text = titleLable[indexPath.row];
    
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                   bundle:nil];
//    if (indexPath.row == 8) {
//        CompetitionoViewC *convc = [main instantiateViewControllerWithIdentifier:@"CompetitionoViewC"];
//        [self.navigationController pushViewController:convc animated:YES];   
//    }
//    
//    if (indexPath.row == 9) {
//        WarViewController *warvc = [main instantiateViewControllerWithIdentifier:@"WarViewController"];
//        [self.navigationController pushViewController:warvc animated:YES];
//    }
    
    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5|| indexPath.row == 6 || indexPath.row == 7){
        VenuelistViewC *wenvc = [main instantiateViewControllerWithIdentifier:@"VenuelistViewC"];
        wenvc.type = titleLable[indexPath.row];
        wenvc.itype = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        [self.navigationController pushViewController:wenvc animated:YES];
    }
    
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88.f;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MainListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefautCellIdentifier"
                                                            forIndexPath:indexPath];
    PlaceEntity *placeEntity = dataArray[indexPath.row];
    
    cell.nameLab.text = placeEntity.name;
    
    NSString *eva = [NSString stringWithFormat:@"%@评论",
                     placeEntity.evaluationCount];
    cell.evaLab.text = eva;
    NSString *now = [NSString stringWithFormat:@"%@",
                     placeEntity.nowPrice];
    cell.nowLab.text = now;
    NSString *ori = [NSString stringWithFormat:@"%@元",
                     placeEntity.originalPrice];
    cell.oriLab.text = ori;
    cell.placeLab.text = placeEntity.address;
    NSString *dis = [NSString stringWithFormat:@"%@km",
                     placeEntity.distance];
    cell.disLab.text = dis;
    NSString *level = [NSString stringWithFormat:@"%@",
                       placeEntity.level];
    NSString *levelImg = [Util getstrWithstarNum:level];
    cell.levelImg.image = [UIImage imageNamed:levelImg];
    NSString *img = [NSString stringWithFormat:@"http://218.93.12.178:8080/hhw-api/%@",
                     placeEntity.imgPath];
    NSURL *url = [NSURL URLWithString:img];
    [cell.placeImg setImageWithURL:url];
    
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                   bundle:nil];
    PlaceDetailViewC *placevc = [main instantiateViewControllerWithIdentifier:@"PlaceDetailViewC"];
    placevc.currentPlace = dataArray[indexPath.row];
    [self.navigationController pushViewController:placevc animated:YES];
    
}



@end
